import React, { Component } from 'react'
import  './From'
import From from './From'
// import './List'
import List from './List'
import './todo.css'
import './comon.scss'
import Add from './Add'

export default class Todo extends Component {

    constructor(){
        super();
        this.state={
            keyword:'',
            showEdit:false,
            currentTodo:{},
            datalist:[]
        }
    }

    handleDel(id){
        this.state.datalist.find((item,index)=>{
            if(item.id === id){
                this.state.datalist.splice(index,1)
                return true;
            }
        })
        this.setState({})
    }
    
    handleEdit(id){
        let todo = this.state.datalist.find((item,index)=>{
            if(item.id === id){
                
                return true;
            }
        })
        this.setState({
            currentTodo:todo,
            showEdit:true
        })
        this.setState({
            
        })
    }
    handleAdd(name){
        // debugger;
        console.log(name);
        this.state.datalist.push({
            id:new Date().getTime(),
            name
        })
        this.setState({})
    }

    handleSearch(keyword){
        this.setState({
            keyword
        })
    }

    handleSubmit = () => {
        let txt = this.refs.name.value;
        this.state.datalist.find((item, index) => {
          if (item.id === this.state.currentTodo.id) {
            this.state.datalist[index].name=txt;
            return true;
          }
        })
        this.setState({
          showEdit:false
        })
        
      }

      handleQu = () => {
          this.setState({
              showEdit:false
          })
      }
    render() {

        let list = this.state.datalist.filter((item,index)=>{
            return item.name.indexOf(this.state.keyword)>-1;
        })

        let deit = <Add title="修改" >
            <input type="text" ref="name" defaultValue={this.state.currentTodo.name}/>
            <button onClick={this.handleSubmit}>提交</button>
            <button onClick={this.handleQu}>取消</button>
        </Add>
        return (
            <div>
                <From add={(name)=>this.handleAdd(name)}
                search={(name)=>this.handleSearch(name)}
                ></From>
                <List list={list} del={(id)=>this.handleDel(id)} edit={(id)=>this.handleEdit(id)}></List>
                {
                    this.state.showEdit ? deit : ''
                }
                
            </div>
        )
    }
}
